<?php
namespace App\Admin\Controllers\Quality;

use App\Admin\Ajax\Quality\ComplaintAjax;
use App\Func\UploadFile;
use App\Models\Basics\SysCountry;
use App\Models\Basics\SysArea;
use App\Models\Basics\SysICountry;
use App\Models\Product\ProductAmazonSku;
use App\Models\Product\ProductClassify;
use App\Models\Product\ProductSku;
use App\Models\Quality\QComplaint;
use App\Models\Quality\QDictTag;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;
class ComplaintController extends AdminController{

    protected $title = '客诉管理';

    protected $filters = [
        'start_date' => null,
        'end_date' => null,
        'order_no' => null,
        'sku' => null,
        'origin' => null,
        'area_id' => [],
        'country_id' => [],
        'classify_id' => [],
        'status' => null,
        'tag' => null,
    ];

    protected function grid()
    {
        $filtersField = array_keys($this->filters);
        $filters = $this->_getFilters($filtersField);
        $this->_initFilters($filters);
        $query = $this->_initQuery($filters);
        $paginator = $this->_paginator($query);
        $action = getAction($filtersField);
        $filtersBlade = [];
        $filtersBlade['start_date'] = $this->filters['start_date'];
        $filtersBlade['end_date'] = $this->filters['end_date'];
        $filtersBlade['order_no'] = $this->filters['order_no'];
        $filtersBlade['origin'] = getOptions(QComplaint::$_origin,$this->filters['origin']);
        $filtersBlade['area_id'] = getMultipleOptions(SysArea::options(),$this->filters['area_id']);
        $filtersBlade['country_id'] = getMultipleOptions(SysICountry::options(),$this->filters['country_id']);
        $filtersBlade['classify_id'] = getMultipleOptions(ProductClassify::options(),$this->filters['classify_id']);
        $filtersBlade['sku'] = $this->filters['sku'];
        $filtersBlade['tag'] = getOptions([1 =>'空',2=>'不为空'],$this->filters['tag']);;
        $filtersBlade['status'] = getOptions(QComplaint::$_status,$this->filters['status']);
        $downloadUrl = '/xqc/quality/complaint-download?' . http_build_query(array_merge(Request::all(),['_export_' => true]));
        return view('quality.complaint.index', compact('paginator','filtersBlade','action','downloadUrl'));
    }

    private function _getFilters($filtersField){
        $startDate = request('start_date');
        $endDate = request('end_date');
        $reportDate = $this->__reportDate($startDate,$endDate);
        $filters = [];
        foreach ($filtersField as $field){
            if(array_key_exists($field,$reportDate)){
                $filters[$field] = $reportDate[$field];
            }elseif(in_array($field,['area_id','country_id','classify_id'])){
                $filters[$field] = request($field,[]);
            }else{
                $filters[$field] = request($field);
            }
        }
        return $filters;
    }

    private function __reportDate($start,$end){
        if(is_null($start) && is_null($end)){
            $startDate = date('Y-m-01');
            $endDate = date('Y-m-d');
        }elseif(!is_null($start) && is_null($end)){
            $startDate = $start;
            $endDate = date('Y-m-t',strtotime($start));
        }elseif(is_null($start) && !is_null($end)){
            $startDate = date('Y-m-01',strtotime($end));
            $endDate = $end;
        }else{
            $startDate = $start;
            $endDate = $end;
        }
        return ['start_date' => $startDate,'end_date' => $endDate];
    }

    private function _initFilters($filters){
        foreach ($filters as $field => $filter){
            $this->filters[$field] = $filter;
        }
    }

    private function _initQuery($filters){
        $query = QComplaint::query()->orderBy('id','DESC');
        foreach ($filters as $field => $filter){
            if(!$filter || is_null($filter) || empty($filter))continue;
            if($field == 'start_date'){
                $query->where('report_date','>=',$filter);
            }
            if($field == 'end_date'){
                $query->where('report_date','<=',$filter);
            }
            if($field == 'tag'){
                if ($filter == 1) {
                    $query->whereNull('tag'); //标签为空
                }
                if ($filter == 2) {
                    $query->whereNotNull('tag'); //标签不为空
                }
            }
            if($field == 'sku'){
                $query->whereHas('sku', function ($query) use($filter){
                    $query->where('psku_code', 'like', "%{$filter}%")
                        ->orWhere('psku_cn', 'like', "%{$filter}%");
                });
            }
            if(in_array($field,['area_id','country_id','classify_id'])){
                $query->whereIn($field,$filter);
            }
            if(in_array($field,['order_no','origin','status'])){
                $query->where($field,$filter);
            }
        }
        return $query;
    }

    private function _paginator($query){
        return $query->paginate((int) (request("per_page",10)))->appends(Request::input());
    }

    protected function form()
    {
        $form = new Form(new QComplaint());
        $form->hidden('id');

        $form->date('report_date', '日期')->format('YYYY-MM-DD')->style('width','150px')->required()->rules('required');
        $form->select('country_id','国家')->options(SysCountry::options())->required()->rules('required')->setWidth(3);
        $form->radio('origin','来源')->options(QComplaint::$_origin)->default(9)->required()->rules('required');
        $form->text('order_no','订单号')->help('若有订单号，请务必输入订单号')->style('width','300px');
        $form->text('seller_sku','平台SKU')->style('width','300px');
        $form->text('asin','ASIN')->style('width','300px');
        $form->select('psku_id', '产品SKU')
            ->options(function ($id) {
                $id = $id ?: old('psku_id');
                $ps = ProductSku::getModelById($id);
                if ($ps) {
                    return [$ps->id => $ps->psku_code];
                }else{
                    return [];
                }
            })->ajax('/xqc/api-sys/products-vague-sku')
            ->help('若平台SKU和ASIN均无法提供，请尽可能提供产品SKU')
            ->setWidth(3);
        $form->select('classify_id','品类')
            ->options(ProductClassify::options())
            ->help('若平台SKU，ASIN和产品SKU均无法提供，请务必选择品类')
            ->setWidth(3);

        $form->textarea('content','反馈内容')->required()->rules('required')->setWidth(5);
        $form->multipleImage('image.pics','图片')->removable()->sortable()->setWidth(5);
        $form->hidden('operator_id')->value(Admin::user()->id);
        $form->hidden('status')->value(0);
        $form->hidden('area_id');

        $form->saving(function (Form $form) {

            if($form->isEditing()){
                if(!is_null($form->country_id) && $form->model()->country_id != $form->country_id){
                    $form->area_id = SysICountry::getAreaIdByCountryId($form->country_id);
                }
            }else{
                $form->area_id = SysICountry::getAreaIdByCountryId($form->country_id);
            }

            if(!($form->image && array_key_exists('pics',$form->image) && $form->image['pics'] == '_file_del_')){
                if($form->seller_sku){
                    $pas = ProductAmazonSku::query()
                        ->where('country_id',$form->country_id)
                        ->where('seller_sku',$form->seller_sku)
                        ->first();
                    if(!$pas){
                        admin_toastr('系统不存在该亚马逊SKU！','error');
                        return back()->withInput();
                    }
                    $form->psku_id = $pas->psku_id;
                    $ps = ProductSku::getModelById($pas->psku_id);
                    $form->classify_id = $ps->classify_id;
                }elseif($form->asin){
                    $pas = ProductAmazonSku::query()
                        ->where('country_id',$form->country_id)
                        ->where('child_asin',$form->asin)
                        ->first();
                    if(!$pas){
                        admin_toastr('系统未匹配到该ASIN！','error');
                        return back()->withInput();
                    }
                    $form->psku_id = $pas->psku_id;
                    $ps = ProductSku::getModelById($pas->psku_id);
                    $form->classify_id = $ps->classify_id;
                }elseif($form->psku_id){
                    $ps = ProductSku::getModelById($form->psku_id);
                    if(!$ps){
                        admin_toastr('系统未匹配到该SKU！','error');
                        return back()->withInput();
                    }
                    $form->classify_id = $ps->classify_id;
                }else{
                    if(!$form->classify_id){
                        admin_toastr('平台SKU，ASIN，产品SKU，品类不能同时为空！','error');
                        return back()->withInput();
                    }else{
                        $form->psku_id = null;
                    }
                }
                $form->content = str_replace(["\r","\n","\r\n"],'',trim($form->content));
            }
//            $query = QComplaint::query()->where('content',$form->content);
//            if($form->psku_id){
//                $query->where('psku_id',$form->psku_id);
//            }elseif($form->classify_id){
//                $query->where('classify_id',$form->classify_id);
//            }
//            $count = $query->count();
//            if($count > 0){
//                admin_toastr('请勿重复添加！','error');
//                return back()->withInput();
//            }
        });

        return $form;
    }

//    protected function delPic($id)
//    {
//        try{
//            if(request()->has('image')){
//                if(array_key_exists('pics',request('image')) && request('image')['pics'] == '_file_del_'){
//                    DB::beginTransaction();
//                    $q = QComplaint::query()->find($id);
//                    $pic = $q->image->pics ?? [];
//                    if($pic){
//                        $index = request('key');
//                        $uf = UploadFile::getInit();
//                        $flag = $uf->delFile($pic[$index]);
//                        if($flag){
//                            unset($pic[$index]);
//                            $q->image->pics = $pic;
//                            $q->image->save();
//                        }
//                    }
//                    DB::commit();
//                }
//            }
//            return response()->json(['status' => true, 'message' => "操作成功！"]);
//        }catch (\Exception $e){
//            DB::rollBack();
//            report($e);
//            return response()->json(['status' => false, 'message' => '操作失败！']);
//        }
//    }

    public function destroy($idStr){
        try{
            DB::beginTransaction();
            $qs = QComplaint::query()->whereIn('id',explode(',',$idStr))->where('status',0)->get();
            $i = 0;
            foreach ($qs as $q){
                if($q->status != 0)continue;
                $q->delete();
                $i++;
            }
            DB::commit();
            return response()->json(['status' => true, 'message' => "成功删除{$i}条记录！"]);
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => '操作失败！']);
        }
    }

    public function download(){
        $filtersField = array_keys($this->filters);
        $filters = $this->_getFilters($filtersField);
        $query = $this->_initQuery($filters);
        $query->with(['classify','area','country','sku']);
        $this->_exeDownload($query);
    }

    private function _exeDownload($query){
        $head = ['日期','站点','国家','来源','订单号','SKU','品名','品类','平台SKU','尺码问题','做工问题','设计问题','主观问题','其它问题','反馈内容'];
        set_time_limit(0);
        $response = new StreamedResponse(null, 200, [
            'Content-Type'        => 'text/csv;charset=utf-8',
            'Content-Disposition' => 'attachment;filename="客诉管理.csv"',
        ]);
        $response->setCallback(function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->chunk(800, function ($re) use ($fp){
                $data = QComplaint::getData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
            fclose($fp);
        });
        $response->send();
        exit(0);
    }

    public function ajax(){
        $action = request('action');
        $param = request('param');
        $ajax = new ComplaintAjax();
        return $param ? call_user_func([$ajax,$action],$param) : call_user_func([$ajax,$action]);
    }

    public function modal(){
        $action = request('action');
        $param = request('param');
        $modal = new ComplaintAjax();
        return $param ? call_user_func([$modal,$action],$param) : call_user_func([$modal,$action]);
    }
}
